package services.intermediate

import models.outstock._

import java.time.{LocalDate, LocalDateTime}
import java.time.format.DateTimeFormatter
import javax.inject.{Inject, Singleton}
import play.api.Logging
import play.api.libs.json.{JsValue, Json}
import services.OutStockPostParameters
import services.kingdee.KingdeePostV1
import utiliy.OutFilterConfig

import scala.collection.mutable.ListBuffer
import scala.concurrent.{Await, ExecutionContext, Future}
import scala.concurrent.duration.Duration

@Singleton
class SendOutStockSum @Inject()(
                                 ossRep: OutStockSumRepository,
                                 kdPost: KingdeePostV1,
                                 ofc: OutFilterConfig,
                                 baseInfomation: BaseInfomation
                               )(implicit exec: ExecutionContext)
  extends Logging {
  /**
   *
   * @param p
   * p2 nonEmpty is sendOSS as default status=2
   * @return
   */
  def sendOSS(p: OutStockPostParameters) = {
    logger.debug(p.toString)
    var result = new ListBuffer[String]
    if (p.p2.nonEmpty) {
      result += postAtDays()
    } else if (p.p1.isEmpty) {
      var startDate, endDate = LocalDate.now()
      try {
        startDate = LocalDate.parse(p.sdate.substring(0, 10)) //.atZone(ZoneId.systemDefault()).toInstant
        endDate = LocalDate.parse(p.sdate.substring(13)) //.atZone(ZoneId.systemDefault()).toInstant
      } catch {
        case e: Exception => logger.debug(s"sendOSS => sdate输入错误:", e);
      }
      logger.info("sendOSS" + startDate + " ~ " + endDate)
      var dateEnd = startDate
      while (dateEnd.compareTo(endDate) <= 0) {
        logger.info(dateEnd.toString)
        val startDate = LocalDateTime.parse(dateEnd.toString + "T00:00:00")
        val endDate = LocalDateTime.parse(dateEnd.toString + "T00:00:00").plusDays(1)
        result += postAtDays(startDate = Some(startDate), endDate = Some(endDate), status = p.status)
        dateEnd = dateEnd.plusDays(1)
      }

    }
    else {
      try {
        val pOutStockSumId = Option(p.p1.substring(4).toInt)
        result += postAtDays(sumId = pOutStockSumId)
      } catch {
        case e: Exception => logger.debug(s"OutStockSumId输入错误", e);
      }
    }
    result

  }

  /**
   * 2C店铺同步到“B2C销售出库单”数据处理
   *
   * @param ossInfo  发货单信息
   * @param ossFeRes 商品明细信息
   * @return
   */

  protected def getToCParamSCM(ossInfo: OutStockSum, ossFeRes: Seq[OutStockSumFEntity]) = {
    val dtformat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    // post
    val ossfe = ossFeRes.map(ossfeInfo =>
      "{" +
        s""""FAllAmount":${ossfeInfo.ossFAllAmount},""" +
        s""""FAmount":${ossfeInfo.ossFAmount},""" +
        s""""FDiscount":${ossfeInfo.ossFDiscount},""" +
        s""""FEOwnerNumber":null,""" +
        s""""FEOwnerTypeId":null,""" +
        s""""FExpiryDate":"1971-01-01 00:00:00",""" +
        s""""FFeeAmount":${ossfeInfo.ossFFeeAmount},""" +
        s""""FGYEntryID":${ossInfo.id.getOrElse(0)},""" +
        s""""FIsFree":${ossfeInfo.ossFIsFree},""" +
        s""""FLotNumber":2018,""" +
        s""""FMaterialNumber":"${ossfeInfo.ossFMaterialNumber}",""" +
        s""""FORDERBILLNO":${ossInfo.id.getOrElse(0)},""" +
        s""""FPrice":${ossfeInfo.ossFPrice},""" +
        s""""FProduceDate":"1971-01-01 00:00:00",""" +
        s""""FQty":${ossfeInfo.ossFQty},""" +
        s""""FSKUNumber":"${ossfeInfo.ossFMaterialNumber}",""" +
        s""""FSerialNo":null,""" +
        s""""FServiceAmount":${ossfeInfo.ossFServiceAmount},""" +
        s""""FTaxAmount":null,""" +
        s""""FTaxRate":null""" +
        "}")
    val receiver_address = ossInfo.ossSumInfo.formatted("sss")
    val para = "{" +
      s""""Creator":null,""" +
      s""""Model":{""" +
      s""""FAddress":"${receiver_address}",""" +
      s""""FBuyerNick":"${ossInfo.ossFShopNumber}",""" +
      s""""FConsignee":"${ossInfo.ossFShopNumber}",""" +
      s""""FCustNumber":null,""" +
      s""""FDate":"${ossInfo.ossFDate.toLocalDateTime.format(dtformat)}",""" +
      s""""FEntity":[${ossfe.toArray.mkString(",")}],""" +
      s""""FGYBillId":${ossInfo.id.getOrElse(0)},""" +
      s""""FGYBillNo":"${ossInfo.ossFGYBillNo}",""" +
      s""""FInvoiceAmount":null,""" +
      s""""FInvoiceContent":null,""" +
      s""""FInvoiceNumber":null,""" +
      s""""FInvoiceTitle":null,""" +
      s""""FInvoiceType":null,""" +
      s""""FMemo":null,""" +
      s""""FOrderNo":null,""" +
      s""""FOwnerNumber":null,""" +
      s""""FOwnerTypeId":null,""" +
      s""""FReceiverAddress":"${receiver_address}",""" +
      s""""FReceiverCity":"广州市",""" +
      s""""FReceiverCountry":"中国",""" +
      s""""FReceiverDistrict":"district",""" +
      s""""FReceiverMobile":"18300023",""" +
      s""""FReceiverName":"${ossInfo.ossFShopNumber}",""" +
      s""""FReceiverPhone":"18300023",""" +
      s""""FReceiverState":"广东省",""" +
      s""""FReceiverZip":null,""" +
      s""""FShopNumber":"${ossInfo.ossFShopNumber}",""" +
      s""""FStockNumber":"${ossInfo.ossFStockNumber}",""" +
      s""""FTaxRegisterCode":null""" +
      "}," +
      s""""NeedReturnFields":null,""" +
      s""""NeedUpDateFields":null,""" +
      s""""SubSystemId":null,""" +
      s""""deleteEntry":null,""" +
      s""""verifyBaseDataField":null""" +
      "}"
    //println(para)
    para
  }


  /**
   * 2C店铺同步到“B2C销售出库单”数据处理
   *
   * @param ossInfo  发货单信息
   * @param ossFeRes 商品明细信息
   * @return
   */
  protected def getXSCKDToCParamBOS(ossInfo: OutStockSum, ossFeRes: Seq[OutStockSumFEntity]) = {
    val dtformat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    val custom = ofc.getShopInfo(ossInfo.ossFShopNumber)
    val kdStock = baseInfomation.getKdStockCode(ossInfo.ossFStockNumber)
    var serviveAmount: Double = 0.0
    var feeAmount: Double = 0.0
    val billNo = "XSCKD" +
      ossInfo.ossFDate.toLocalDateTime.format(DateTimeFormatter.ofPattern("yyMM")) +
      kdPost.signCode(custom.org.takeRight(3)) + "C" +
      ("00000000" + ossInfo.id.getOrElse(0).toString).takeRight(8)
    val FEntryTaxRate = 13.0 //  税率
    var ossfe = ossFeRes.map {
      ossfeInfo => {
        val kdMaterial = baseInfomation.getKdMaterialCode(ossfeInfo.ossFMaterialNumber)
        serviveAmount += ossfeInfo.ossFServiceAmount
        feeAmount += ossfeInfo.ossFFeeAmount
        val qty = ossfeInfo.ossFQty
        val FDiscount = ossfeInfo.ossFDiscount
        val FTaxPrice = ossfeInfo.ossFPrice
        val FAllAmount = ossfeInfo.ossFAllAmount
        val FAmount = FAllAmount /(1 + FEntryTaxRate / 100.0)
        val FEntryTaxAmount = FAllAmount - FAmount
        val FPrice = FTaxPrice /(1 + FEntryTaxRate / 100.0)
        val FDiscountRate = (FDiscount / (FDiscount + FAllAmount)) * 100
        val FTaxNetPrice = FAllAmount / qty
        s"""{
           | "FMaterialID":{"FNumber":"${kdMaterial.kdNumber}"},
           | "FUnitID":{"FNumber":"${kdMaterial.kdBaseUnit}"},
           | "FMustQty":$qty,
           | "FRealQty":$qty,
           | "FPrice": $FPrice,
           | "FTaxPrice":$FTaxPrice,
           | "FEntryTaxRate": $FEntryTaxRate,
           | "FDiscountRate": $FDiscountRate,
           | "FDiscount":$FDiscount,
           | "FAmount": $FAmount,
           | "FEntryTaxAmount": $FEntryTaxAmount,
           | "FAllAmount": $FAllAmount,
           | "FTaxNetPrice":$FTaxNetPrice,
           | "FLot":{"FNumber":"2018"},
           | "FOwnerTypeID":"BD_OwnerOrg",
           | "FOwnerID":{"FNumber":"${kdStock.org}"},
           | "FStockID":{"FNumber":"${kdStock.kdFNumber}"},
           | "FIsFree":false,
           | "FStockStatusID":{"FNumber":"KCZT01_SYS"},
           | "FStockFlag":true,
           | "FSalUnitID":{"FNumber":"${kdMaterial.kdBaseUnit}"},
           | "FETHIRDBILLNO":"${ossInfo.ossFGYBillNo}",
           | "FETHIRDBILLID": "${ossInfo.id.getOrElse(0)}",
           | "FSoorDerno": "${ossInfo.id.getOrElse(0)}"
           |}""".stripMargin
      }
    }
    ossfe = if (serviveAmount > 0) {
      val FTaxPrice = serviveAmount
      val FAllAmount = serviveAmount
      val FAmount = FAllAmount /(1 + FEntryTaxRate / 100.0)
      val FEntryTaxAmount = FAllAmount - FAmount
      val FPrice = FTaxPrice /(1 + FEntryTaxRate / 100.0)
      val wuliu =
        s"""{
           | "FMaterialID":{"FNumber":"F01010021"},
           | "FUnitID":{"FNumber":"Pcs"},
           | "FMustQty":1,
           | "FRealQty":1,
           | "FPrice": $FPrice,
           | "FTaxPrice":$FTaxPrice,
           | "FEntryTaxRate": $FEntryTaxRate,
           | "FAmount": $FAmount,
           | "FEntryTaxAmount": $FEntryTaxAmount,
           | "FAllAmount": $FAllAmount,
           | "FOwnerTypeID":"BD_OwnerOrg",
           | "FOwnerID":{"FNumber":"${kdStock.org}"},
           | "FStockID":{"FNumber":"${kdStock.kdFNumber}"},
           | "FIsFree":false,
           | "FStockStatusID":{"FNumber":"KCZT01_SYS"},
           | "FStockFlag":true,
           | "FSalUnitID":{"FNumber":"Pcs"},
           | "FETHIRDBILLNO":"${ossInfo.ossFGYBillNo}",
           | "FETHIRDBILLID": "${ossInfo.id.getOrElse(0)}",
           | "FSoorDerno": "${ossInfo.id.getOrElse(0)}"
           |}""".stripMargin
      ossfe :+ wuliu
    } else ossfe
    ossfe = if (feeAmount > 0) {
      val FTaxPrice = feeAmount
      val FAllAmount = feeAmount
      val FEntryTaxAmount = FAllAmount * FEntryTaxRate / 100.0
      val FAmount = FAllAmount - FEntryTaxAmount
      val FPrice = FTaxPrice * FEntryTaxRate / 100.0
      val fee =
        s"""{
           | "FMaterialID":{"FNumber":"FeeAmount"},
           | "FUnitID":{"FNumber":"Pcs"},
           | "FMustQty":1,
           | "FRealQty":1,
           | "FPrice": $FPrice,
           | "FTaxPrice":$FTaxPrice,
           | "FEntryTaxRate": $FEntryTaxRate,
           | "FAmount": $FAmount,
           | "FEntryTaxAmount": $FEntryTaxAmount,
           | "FAllAmount": $FAllAmount,
           | "FOwnerTypeID":"BD_OwnerOrg",
           | "FOwnerID":{"FNumber":"${kdStock.org}"},
           | "FStockID":{"FNumber":"${kdStock.kdFNumber}"},
           | "FIsFree":false,
           | "FStockStatusID":{"FNumber":"KCZT01_SYS"},
           | "FStockFlag":true,
           | "FSalUnitID":{"FNumber":"Pcs"},
           | "FETHIRDBILLNO":"${ossInfo.ossFGYBillNo}",
           | "FETHIRDBILLID": "${ossInfo.id.getOrElse(0)}",
           | "FSoorDerno": "${ossInfo.id.getOrElse(0)}"
           |}""".stripMargin
      ossfe :+ fee
    } else ossfe
    val para =
      s"""{
         |"InterationFlags": "STK_InvCheckResult",
         |"IsAutoSubmitAndAudit": "false",
         |"Model": {
         |    "FBillNo": "$billNo",
         |    "FBillTypeID": {"FNUMBER": "XSCKD07_SYS"},
         |    "FDate": "${ossInfo.ossFDate.toLocalDateTime.format(dtformat)}",
         |    "FSaleOrgId": {"FNumber": "${custom.org.takeRight(3)}"},
         |    "FCustomerID": {"FNumber": "${custom.kdNo}"},
         |    "FStockOrgId": {"FNumber": "${kdStock.org}"},
         |    "FDeliveryDeptID": {"FNumber": "${custom.deptId}"},
         |    "FNote": "【${custom.code}】${custom.name}",
         |    "FReceiverID": {"FNumber": "${custom.kdNo}"},
         |    "FSettleID": {"FNumber": "${custom.kdNo}"},
         |    "FPayerID": {"FNumber": "${custom.kdNo}"},
         |    "FOwnerTypeIdHead": "BD_OwnerOrg",
         |    "FOwnerIdHead": {"FNumber": "${kdStock.org}"},
         |    "FReceiveAddress": "sss",
         |    "SubHeadEntity": {
         |        "FSettleOrgID": {"FNumber": "${custom.org.takeRight(3)}"},
         |        "FThirdBillNo": "${ossInfo.ossFGYBillNo}",
         |        "FThirdBillId": "${ossInfo.id.getOrElse(0)}",
         |        "FThirdSrcType": "1"
         |    },
         |    "FEntity": [
         |     ${ossfe.mkString(",")}
         |     ]
         | }
         |}""".stripMargin
    Json.parse(para)
  }

  /**
   * 2B店铺同步到“标准销售出库单(代销)”数据处理
   *
   * @param ossInfo  发货单信息
   * @param ossFeRes 商品明细信息
   * @return
   */
  protected def getXSCKDToBParamBOS(ossInfo: OutStockSum, ossFeRes: Seq[OutStockSumFEntity]) = {
    val dtformat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    val custom = ofc.getShopInfo(ossInfo.ossFShopNumber)
    val kdStock = baseInfomation.getKdStockCode(ossInfo.ossFStockNumber)
    var serviveAmount: Double = 0.0
    var feeAmount: Double = 0.0
    val billNo = "XSCKD" +
      ossInfo.ossFDate.toLocalDateTime.format(DateTimeFormatter.ofPattern("yyMM")) +
      kdPost.signCode(custom.org.takeRight(3)) + "D" +
      ("00000000" + ossInfo.id.getOrElse(0).toString).takeRight(8)
    val FEntryTaxRate = 13.0 //  税率
    val ossfe = ossFeRes.map {
      ossfeInfo => {
        val kdMaterial = baseInfomation.getKdMaterialCode(ossfeInfo.ossFMaterialNumber)
        serviveAmount += ossfeInfo.ossFServiceAmount
        feeAmount += ossfeInfo.ossFFeeAmount
        val qty = ossfeInfo.ossFQty
        val FDiscount = ossfeInfo.ossFDiscount
        val FTaxPrice = ossfeInfo.ossFPrice
        val FAllAmount = ossfeInfo.ossFAllAmount
        val FAmount = FAllAmount /(1 + FEntryTaxRate / 100.0)
        val FEntryTaxAmount = FAllAmount - FAmount
        val FPrice = FTaxPrice /(1 + FEntryTaxRate / 100.0)
        val FDiscountRate = FDiscount / (FDiscount + FAllAmount)
        val FTaxNetPrice = FAllAmount / qty
        s"""{
           | "FMaterialID":{"FNumber":"${kdMaterial.kdNumber}"},
           | "FUnitID":{"FNumber":"${kdMaterial.kdBaseUnit}"},
           | "FMustQty":$qty,
           | "FRealQty":$qty,
           | "FPrice": $FPrice,
           | "FTaxPrice":$FTaxPrice,
           | "FEntryTaxRate": $FEntryTaxRate,
           | "FDiscountRate": $FDiscountRate,
           | "FDiscount":$FDiscount,
           | "FAmount": $FAmount,
           | "FEntryTaxAmount": $FEntryTaxAmount,
           | "FAllAmount": $FAllAmount,
           | "FTaxNetPrice":$FTaxNetPrice,
           | "FLot":{"FNumber":"2018"},
           | "FOwnerTypeID":"BD_OwnerOrg",
           | "FOwnerID":{"FNumber":"${kdStock.org}"},
           | "FStockID":{"FNumber":"${kdStock.kdFNumber}"},
           | "FIsFree":false,
           | "FStockStatusID":{"FNumber":"KCZT01_SYS"},
           | "FStockFlag":true,
           | "FSalUnitID":{"FNumber":"${kdMaterial.kdBaseUnit}"},
           | "FETHIRDBILLNO":"${ossInfo.ossFGYBillNo}",
           | "FETHIRDBILLID": "${ossInfo.id.getOrElse(0)}",
           | "FSoorDerno": "${ossInfo.id.getOrElse(0)}"
           |}""".stripMargin
      }
    }

    val para =
      s"""{
         | "InterationFlags": "STK_InvCheckResult",
         | "IsAutoSubmitAndAudit": "true",
         | "Model": {
         |     "FBillNo": "$billNo",
         |     "FBillTypeID": {"FNUMBER": "XSCKD08_SYS"},
         |     "FDate": "${ossInfo.ossFDate.toLocalDateTime.format(dtformat)}",
         |     "FSaleOrgId": {"FNumber": "${custom.org.takeRight(3)}"},
         |     "FCustomerID": {"FNumber": "${custom.kdNo}"},
         |     "FStockOrgId": {"FNumber": "${kdStock.org}"},
         |     "FDeliveryDeptID": {"FNumber": "${custom.deptId}"},
         |     "FSaleDeptID": {"FNumber": "${custom.deptId}"},
         |     "FNote": "(${custom.code})${custom.name}",
         |     "FReceiverID": {"FNumber": "${custom.kdNo}"},
         |     "FSettleID": {"FNumber": "${custom.kdNo}"},
         |     "FPayerID": {"FNumber": "${custom.kdNo}"},
         |     "FOwnerTypeIdHead": "BD_OwnerOrg",
         |     "FIsTotalServiceOrCost": false,
         |     "F_PAEZ_CheckBox": false,
         |     "SubHeadEntity": {
         |         "FSettleOrgID": {"FNumber": "${custom.org.takeRight(3)}"},
         |         "FThirdBillNo": "${ossInfo.ossFGYBillNo}",
         |         "FThirdBillId": "${ossInfo.id.getOrElse(0)}",
         |         "FThirdSrcType": "1"
         |     },
         |     "FEntity": [
         |     ${ossfe.mkString(",")}
         |     ]
         | }
         |}""".stripMargin
    Json.parse(para)
  }

  /**
   * 同步到“销售出库单”数据处理，“标准销售出库单(代销)”与“B2C销售出库单”
   *
   * @param ossInfo  发货单信息
   * @param ossFeRes 商品明细信息
   * @return
   */
  def getXSCKDParamBOS(ossInfo: OutStockSum, ossFeRes: Seq[OutStockSumFEntity]) = {
    if (ofc.isToBShop(ossInfo.ossFShopNumber)) {
      getXSCKDToBParamBOS(ossInfo, ossFeRes)
    } else {
      getXSCKDToCParamBOS(ossInfo, ossFeRes)
    }
  }

  /**
   * 2C店铺同步到“B2C销售退货单”数据处理
   *
   * @param ossInfo  退货单信息
   * @param ossFeRes 商品明细信息
   */
  protected def getXSTHDToCParamBOS(ossInfo: OutStockSum, ossFeRes: Seq[OutStockSumFEntity]) = {
    val dtformat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    val custom = ofc.getShopInfo(ossInfo.ossFShopNumber)
    val kdStock = baseInfomation.getKdStockCode(ossInfo.ossFStockNumber)
    var feeAmount: Double = 0.0
    val billId = "\\d".r.findAllIn(ossInfo.ossFGYBillNo).mkString.toLong
    val billNo = "XSTHD" +
      ossInfo.ossFDate.toLocalDateTime.format(DateTimeFormatter.ofPattern("yyMM")) +
      kdPost.signCode(custom.org.takeRight(3)) + "C" +
      ("00000000" + java.lang.Long.toString(billId, 36).toUpperCase).takeRight(8)
    val FEntryTaxRate = 13.0 //  税率
    var ossfe = ossFeRes.map {
      ossfeInfo => {
        val kdMaterial = baseInfomation.getKdMaterialCode(ossfeInfo.ossFMaterialNumber)
        feeAmount += ossfeInfo.ossFFeeAmount
        val qty = ossfeInfo.ossFQty
        val FDiscount = ossfeInfo.ossFDiscount
        val FTaxPrice = ossfeInfo.ossFPrice
        val FAllAmount = ossfeInfo.ossFAllAmount
        val FAmount = FAllAmount /(1 + FEntryTaxRate / 100.0)
        val FEntryTaxAmount = FAllAmount - FAmount
        val FPrice = FTaxPrice /(1 + FEntryTaxRate / 100.0)
        val FDiscountRate = if ((FDiscount + FAllAmount) == 0) 0 else (FDiscount / (FDiscount + FAllAmount)) * 100
        val FTaxNetPrice = FAllAmount / qty
        if(qty==0) ""
        else  s"""
           |{
           |  "FMaterialId": {"FNumber": "${kdMaterial.kdNumber}"},
           |  "FUnitID": {"FNumber": "${kdMaterial.kdBaseUnit}"},
           |  "FLot": {"FNumber": "2018"},
           |  "FMustQty": $qty,
           |  "FRealQty": $qty,
           |  "FTaxPrice": $FTaxPrice,
           |  "FPrice": $FPrice,
           |  "FEntryTaxRate": $FEntryTaxRate,
           |  "FDiscountRate": $FDiscountRate,
           |  "FDiscount": $FDiscount,
           |  "FAmount": $FAmount,
           |  "FEntryTaxAmount": $FEntryTaxAmount,
           |  "FAllAmount": $FAllAmount,
           |  "FIsFree": false,
           |  "FReturnType": {"FNumber": "THLX01_SYS"},
           |  "FOwnerTypeId": "BD_OwnerOrg",
           |  "FOwnerId": {"FNumber": "${kdStock.org}"},
           |  "FStockId": {"FNumber": "${kdStock.kdFNumber}"},
           |  "FStockstatusId": {"FNumber": "KCZT01_SYS"},
           |  "FDeliveryDate": "${ossInfo.ossFDate.toLocalDateTime.format(dtformat)}",
           |  "FSalUnitID": {"FNumber": "${kdMaterial.kdBaseUnit}"},
           |  "FETHIRDBILLNO": "${ossInfo.ossFGYBillNo}",
           |  "FETHIRDBILLID": "$billId"
           |}""".stripMargin
      }
    }
    ossfe = if (feeAmount > 0) {
      val FTaxPrice = feeAmount
      val FAllAmount = feeAmount
      val FAmount = FAllAmount /(1 + FEntryTaxRate / 100.0)
      val FEntryTaxAmount = FAllAmount - FAmount
      val FPrice = FTaxPrice /(1 + FEntryTaxRate / 100.0)
      val fee =
        s"""
           |{
           |  "FMaterialId": {"FNumber": "F01010021"},
           |  "FUnitID": {"FNumber": "Pcs"},
           |  "FLot": {"FNumber": "2018"},
           |  "FMustQty": 1,
           |  "FRealQty": 1,
           |  "FPrice": $FPrice,
           |  "FTaxPrice": $FTaxPrice,
           |  "FEntryTaxRate": $FEntryTaxRate,
           |  "FDiscountRate": 0,
           |  "FDiscount": 0,
           |  "FAmount": $FAmount,
           |  "FEntryTaxAmount": $FEntryTaxAmount,
           |  "FAllAmount": $FAllAmount,
           |  "FIsFree": false,
           |  "FReturnType": {"FNumber": "THLX01_SYS"},
           |  "FOwnerTypeId": "BD_OwnerOrg",
           |  "FOwnerId": {"FNumber": "${kdStock.org}"},
           |  "FStockId": {"FNumber": "${kdStock.kdFNumber}"},
           |  "FStockstatusId": {"FNumber": "KCZT01_SYS"},
           |  "FDeliveryDate": "${ossInfo.ossFDate.toLocalDateTime.format(dtformat)}",
           |  "FSalUnitID": {"FNumber": "Pcs"},
           |  "FETHIRDBILLNO": "${ossInfo.ossFGYBillNo}",
           |  "FETHIRDBILLID": "$billId"
           |}""".stripMargin
      ossfe :+ fee
    } else ossfe
    val ossfefilter = ossfe.filterNot(f=>f.equals(""))
    val para =
      s"""
         |{
         |"InterationFlags": "",
         |"IgnoreInterationFlag": "",
         |"IsControlPrecision": "false",
         |"IsAutoSubmitAndAudit": "false",
         |"Model": {
         |    "FBillNo":"$billNo",
         |    "FBillTypeID": {"FNumber": "XSTHD07_SYS"},
         |    "FDate": "${ossInfo.ossFDate.toLocalDateTime.format(dtformat)}",
         |    "FSaleOrgId": {"FNumber": "${custom.org.takeRight(3)}"},
         |    "FRetcustId": {"FNumber": "${custom.kdNo}"},
         |    "FReturnReason": {"FNumber": "QT"},
         |    "FStockOrgId": {"FNumber": "${kdStock.org}"},
         |    "FHeadNote": "【${custom.code}】${custom.name}",
         |    "FOwnerTypeIdHead": "BD_OwnerOrg",
         |    "FOwnerIdHead":{"FNumber": "${kdStock.org}"},
         |    "SubHeadEntity": {
         |        "FSettleOrgId": {"FNumber": "${custom.org.takeRight(3)}"},
         |        "FThirdBillNo": "${ossInfo.ossFGYBillNo}",
         |        "FThirdBillId": "$billId",
         |        "FThirdSrcType": "1"
         |    },
         |    "FEntity": [${ossfefilter.mkString(",")}]
         |    }
         |}""".stripMargin
    logger.debug(para)
    Json.parse(para)
  }

  /**
   * 2C店铺同步到“标准销售退货单（代销）”数据处理
   *
   * @param ossInfo  退货单信息
   * @param ossFeRes 商品明细信息
   */
  protected def getXSTHDToBParamBOS(ossInfo: OutStockSum, ossFeRes: Seq[OutStockSumFEntity]) = {
    val dtformat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    val custom = ofc.getShopInfo(ossInfo.ossFShopNumber)
    val kdStock = baseInfomation.getKdStockCode(ossInfo.ossFStockNumber)
    var serviveAmount: Double = 0.0
    var feeAmount: Double = 0.0
    val billId = "\\d".r.findAllIn(ossInfo.ossFGYBillNo).mkString.toLong
    val billNo = "XSTHD" +
      ossInfo.ossFDate.toLocalDateTime.format(DateTimeFormatter.ofPattern("yyMM")) +
      kdPost.signCode(custom.org.takeRight(3)) + "B" +
      ("00000000" + java.lang.Long.toString(billId, 36).toUpperCase).takeRight(8)
    val FEntryTaxRate = 13.0 //  税率
    var ossfe = ossFeRes.map {
      ossfeInfo => {
        val kdMaterial = baseInfomation.getKdMaterialCode(ossfeInfo.ossFMaterialNumber)
        serviveAmount += ossfeInfo.ossFServiceAmount
        feeAmount += ossfeInfo.ossFFeeAmount
        val qty = ossfeInfo.ossFQty
        val FDiscount = ossfeInfo.ossFDiscount
        val FTaxPrice = ossfeInfo.ossFPrice
        val FAllAmount = ossfeInfo.ossFAllAmount
        val FAmount = FAllAmount /(1 + FEntryTaxRate / 100.0)
        val FEntryTaxAmount = FAllAmount - FAmount
        val FPrice = FTaxPrice /(1 + FEntryTaxRate / 100.0)
        val FDiscountRate = FDiscount / (FDiscount + FAllAmount)
        val FTaxNetPrice = FAllAmount / qty
        s"""
           |{
           |  "FMaterialId": {"FNumber": "${kdMaterial.kdNumber}"},
           |  "FUnitID": {"FNumber": "${kdMaterial.kdBaseUnit}"},
           |  "FLot": {"FNumber": "2018"},
           |  "FMustQty": $qty,
           |  "FRealQty": $qty,

           |  "FTaxPrice": $FTaxPrice,
           |  "FPrice": $FPrice,
           |  "FEntryTaxRate": $FEntryTaxRate,
           |  "FDiscountRate": $FDiscountRate,
           |  "FDiscount": $FDiscount,
           |  "FAmount": $FAmount,
           |  "FEntryTaxAmount": $FEntryTaxAmount,
           |  "FAllAmount": $FAllAmount,
           |  "FIsFree": false,
           |  "FReturnType": {"FNumber": "THLX01_SYS"},
           |  "FOwnerTypeId": "BD_OwnerOrg",
           |  "FOwnerId": {"FNumber": "${kdStock.org}"},
           |  "FStockId": {"FNumber": "${kdStock.kdFNumber}"},
           |  "FStockstatusId": {"FNumber": "KCZT01_SYS"},
           |  "FDeliveryDate": "${ossInfo.ossFDate.toLocalDateTime.format(dtformat)}",
           |  "FSalUnitID": {"FNumber": "${kdMaterial.kdBaseUnit}"},
           |  "FETHIRDBILLNO": "${ossInfo.ossFGYBillNo}",
           |  "FETHIRDBILLID": "$billId"
           |}""".stripMargin
      }
    }

    val para =
      s"""
         |{
         |  "InterationFlags": "",
         |  "IgnoreInterationFlag": "",
         |  "IsControlPrecision": "false",
         |  "InterationFlags": "STK_InvCheckResult",
         |  "IsAutoSubmitAndAudit": "true",
         |  "Model": {
         |      "FBillNo ":"$billNo",
         |      "FBillTypeID": {"FNUMBER": "XSTHD09_SYS"},
         |      "FDate": "${ossInfo.ossFDate.toLocalDateTime.format(dtformat)}",
         |      "FSaleOrgId": {"FNumber": "${custom.org.takeRight(3)}"},
         |      "FRetcustId": {"FNumber": "${custom.kdNo}"},
         |      "FReturnReason": {"FNumber": "QT"},
         |      "FTransferBizType": {"FNumber": "OverOrgSal"},
         |      "FStockOrgId": {"FNumber": "${kdStock.org}"},
         |      "FStockDeptId": {"FNumber": "${custom.deptId}"},
         |      "FSaledeptid":{"FNumber": "${custom.deptId}"},
         |      "FHeadNote": "【${custom.code}】${custom.name}",
         |      "FReceiveCustId": {"FNumber": "${custom.kdNo}"},
         |      "FSettleCustId": {"FNumber": "${custom.kdNo}"},
         |      "FPayCustId": {"FNumber": "${custom.kdNo}"},
         |      "FOwnerTypeIdHead": "BD_OwnerOrg",
         |      "SubHeadEntity": {
         |          "FSettleOrgId": {"FNumber": "${custom.org.takeRight(3)}"},
         |          "FThirdBillNo": "${ossInfo.ossFGYBillNo}",
         |          "FThirdBillId": "$billId",
         |          "FThirdSrcType": "1"
         |      },
         |      "FEntity": [${ossfe.mkString(",")}]
         |  }
         |}""".stripMargin
    logger.debug(para)
    Json.parse(para)
  }

  /**
   * 同步到“销售退货单”数据处理，“标准销售退货单（代销）”与“B2C销售退货单”
   *
   * @param ossInfo  退货单信息
   * @param ossFeRes 商品明细信息
   */
  def getXSTHDParamBOS(ossInfo: OutStockSum, ossFeRes: Seq[OutStockSumFEntity]) = {
    if (ofc.isToBShop(ossInfo.ossFShopNumber)) {
      getXSTHDToBParamBOS(ossInfo, ossFeRes)
    } else {
      getXSTHDToCParamBOS(ossInfo, ossFeRes)
    }
  }

  /**
   *
   * @param startDate
   * @param endDate
   * @param status
   * @param sumId
   * @return
   */
  def postAtDays(startDate: Option[LocalDateTime] = None,
                 endDate: Option[LocalDateTime] = None,
                 status: Int = 2,
                 sumId: Option[Int] = None) = {
    val startTime = System.currentTimeMillis()
    val dtformat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    logger.info((startDate, endDate, status, sumId).toString)
    val oss = if (sumId.isEmpty) {
      ossRep.ossFind(startDate, endDate, status)
    } else {
      ossRep.ossFind(sumId = sumId, status = 3)
    }
    //Await.result(oss.map(println), Duration.Inf)
    val res = oss.map { s =>
      //println(s)
      s.map { ossInfo =>
        ossRep.ossFeFind(ossInfo.id.getOrElse(0)).map { ossFeRes =>
          //println(ossInfo, ossFeRes)
          //          if (ofc.isToBShop(ossInfo.ossFShopNumber)) {
          //            val tobPara = s"[\"SAL_OUTSTOCK\",${getXSCKDToBParamBOS(ossInfo, ossFeRes)}]"
          //            logger.debug(tobPara)
          //            kdPost.post("Kingdee.BOS.WebApi.ServicesStub.DynamicFormService.Save.common.kdsvc", Json.parse(tobPara))
          //          } else
          if (ofc.isInFShopNumber(ossInfo.ossFShopNumber))
            Future(
              s"""{"Result":{"ResponseStatus":{"IsSuccess":true,"Errors":[],"SuccessEntitys":[
                 |{"Id":${ossInfo.id.getOrElse(0)},"Number":"${ossInfo.ossFGYBillNo}","DIndex":0}],
                 |"SuccessMessages":["此店铺不同步至金蝶"],"MsgCode":0},"Id":${ossInfo.id.getOrElse(0)},
                 |"Number":"${ossInfo.ossFGYBillNo}","NeedReturnData":[{}]}}""".stripMargin)
          else if (ofc.isInFStockNumber(ossInfo.ossFStockNumber))
            Future(
              s"""{"Result":{"ResponseStatus":{"IsSuccess":true,"Errors":[],"SuccessEntitys":[
                 |{"Id":${ossInfo.id.getOrElse(0)},"Number":"${ossInfo.ossFGYBillNo}","DIndex":0}],
                 |"SuccessMessages":["此仓库不同步至金蝶"],"MsgCode":0},"Id":${ossInfo.id.getOrElse(0)},
                 |"Number":"${ossInfo.ossFGYBillNo}","NeedReturnData":[{}]}}""".stripMargin)
          else {
            //            val tocPara = getToCParamSCM(ossInfo, ossFeRes)
            //            kdPost.post(
            //              "Kingdee.K3.SCM.WebApi.ServicesStub.OutStockService.Save.common.kdsvc",
            //              Json.parse("[" + tocPara + "]")
            //            )
            val tobPara = Json.arr("SAL_OUTSTOCK", getXSCKDParamBOS(ossInfo, ossFeRes)) //s"[\"SAL_OUTSTOCK\",${getXSCKDToBParamBOS(ossInfo, ossFeRes)}]"
            logger.debug(tobPara.toString())
            kdPost.webApiSave(tobPara)
          }
        }.andThen(pf => {
          //println(pf);
          pf.map(r => r.map(r => {
            try {
              logger.debug(r)
              val res = Json.parse(r)
              if (res("Result")("ResponseStatus")("IsSuccess").as[Boolean]) {
                ossRep.ossUpdateEnd(
                  OutStockSum(
                    id = ossInfo.id,
                    ossResult = Some(r),
                    ossStatus = 2,
                    ossKDResultID = res("Result")("Number").asOpt[String]
                  )
                )
              } else if (res("Result")("ResponseStatus")("MsgCode").as[Int] == 11) {
                val err = res("Result")("ResponseStatus")("Errors").as[Array[JsValue]]
                val msg = err(0)("Message").as[String]
                if (msg.startsWith("违反字段唯一性要求：编码唯一。") || msg.startsWith("第三方单据编号")) {
                  val resultId = Option("[0-9A-Za-z]".r.findAllIn(msg).mkString)
                  ossRep.ossUpdateEnd(OutStockSum(id = ossInfo.id, ossResult = Some(r), ossStatus = 2, ossKDResultID = resultId))
                } else {
                  ossRep.ossUpdateEnd(OutStockSum(id = ossInfo.id, ossResult = Some(r), ossStatus = 1))
                }
              } else {
                ossRep.ossUpdateEnd(OutStockSum(id = ossInfo.id, ossResult = Some(r), ossStatus = 1))
              }
            } catch {
              case e: Exception => {
                logger.info("SendOutStockSum Json.parse Exception:", e);
                ossRep.ossUpdateEnd(OutStockSum(id = ossInfo.id, ossResult = Some(r), ossStatus = 1))
              }
            }
          }))

        })
        Thread.sleep(100)
      }
    }
    //res.map(println)
    val result = Await.result(res.map(r => r.length), Duration.Inf)

    s"""{"date":"${LocalDateTime.now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))}",
       |"RunTime": ${(System.currentTimeMillis() - startTime) / 1000.0},
       |"sdoCount": $result,
       |"result":"${startDate.getOrElse(LocalDateTime.now).toLocalDate}"}""".stripMargin

  }

  def postAtNotSend(startDate: Option[LocalDateTime] = None,
                    endDate: Option[LocalDateTime] = None,
                    status: Int = 2,
                    sumId: Option[Int] = None) = {
    val startTime = System.currentTimeMillis()
    val dtformat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    val oss = Await.result(if (sumId.isEmpty) {
      ossRep.ossFind(startDate, endDate, status)
    } else {
      ossRep.ossFind(sumId = sumId, status = 3)
    }, Duration.Inf)
    val result = oss.length
    logger.info("postAtNotSend(startDate, endDate, status, sumId, result) = " + (startDate, endDate, status, sumId, result).toString)
    val ossfe = for (ossInfo <- oss)
      yield (ossInfo, Await.result(ossRep.ossFeFind(ossInfo.id.getOrElse(0)), Duration.Inf))

    for (f <- ossfe) {
      val ossFeRes = f._2
      val ossInfo = f._1
      val r =
        if (ofc.isInFShopNumber(ossInfo.ossFShopNumber))
          (
            s"""{"Result":{"ResponseStatus":{"IsSuccess":true,"Errors":[],"SuccessEntitys":[
               |{"Id":${ossInfo.id.getOrElse(0)},"Number":"${ossInfo.ossFGYBillNo}","DIndex":0}],
               |"SuccessMessages":["此店铺不同步至金蝶"],"MsgCode":0},"Id":${ossInfo.id.getOrElse(0)},
               |"Number":"${ossInfo.ossFGYBillNo}","NeedReturnData":[{}]}}""".stripMargin)
        else if (ofc.isInFStockNumber(ossInfo.ossFStockNumber))
          (
            s"""{"Result":{"ResponseStatus":{"IsSuccess":true,"Errors":[],"SuccessEntitys":[
               |{"Id":${ossInfo.id.getOrElse(0)},"Number":"${ossInfo.ossFGYBillNo}","DIndex":0}],
               |"SuccessMessages":["此仓库不同步至金蝶"],"MsgCode":0},"Id":${ossInfo.id.getOrElse(0)},
               |"Number":"${ossInfo.ossFGYBillNo}","NeedReturnData":[{}]}}""".stripMargin)
        else {
          val tobPara = Json.arr("SAL_OUTSTOCK", getXSCKDParamBOS(ossInfo, ossFeRes))
          logger.debug(tobPara.toString())
          Await.result(kdPost.webApiSave(tobPara), Duration.Inf)
        }
      try {
        val res = Json.parse(r)

        /**
         * {
         * "Result": {
         * "ResponseStatus": {
         * "ErrorCode": 500,
         * "IsSuccess": false,
         * "Errors": [{
         * "FieldName": "FBillNo",
         * "Message": "违反字段唯一性要求：编码唯一。[XSCKD103XXSDO10011]在当前系统中已经被使用。",
         * "DIndex": 0
         * }, {
         * "FieldName": "",
         * "Message": "第三方单据编号【XXSDO10011】重复，不允许保存。",
         * "DIndex": 0
         * }],
         * "SuccessEntitys": [],
         * "SuccessMessages": [],
         * "MsgCode": 11
         * },
         * "Id": "",
         * "Number": "",
         * "NeedReturnData": [{}]
         * }
         * }
         */
        if (res("Result")("ResponseStatus")("IsSuccess").as[Boolean]) {
          ossRep.ossUpdateEnd(
            OutStockSum(
              id = ossInfo.id,
              ossResult = Some(r),
              ossStatus = 2,
              ossKDResultID = res("Result")("Number").asOpt[String]
            )
          )
        } else if (res("Result")("ResponseStatus")("MsgCode").as[Int] == 11) {
          val err = res("Result")("ResponseStatus")("Errors").as[Array[JsValue]]
          val msg = err(0)("Message").as[String]
          if (msg.startsWith("违反字段唯一性要求：编码唯一。") || msg.startsWith("第三方单据编号")) {
            val resultId = Option("[0-9A-Za-z]".r.findAllIn(msg).mkString)
            ossRep.ossUpdateEnd(OutStockSum(id = ossInfo.id, ossResult = Some(r), ossStatus = 2, ossKDResultID = resultId))
          } else {
            ossRep.ossUpdateEnd(OutStockSum(id = ossInfo.id, ossResult = Some(r), ossStatus = 1))
          }
        } else {
          ossRep.ossUpdateEnd(OutStockSum(id = ossInfo.id, ossResult = Some(r), ossStatus = 1))
        }
      } catch {
        case e: Exception => {
          logger.debug("SendOutStockSum Json.parse Exception:", e);
          ossRep.ossUpdateEnd(OutStockSum(id = ossInfo.id, ossResult = Some(r), ossStatus = 1))
        }
      }
    }
    s"""{
       |"date":"${LocalDateTime.now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))}",
       |"RunTime": ${(System.currentTimeMillis() - startTime) / 1000.0},
       |"sdoCount": $result,
       |"result":"${startDate.getOrElse(LocalDateTime.now).toLocalDate}"
       |}""".stripMargin
  }

  def postRgoAtNotSend(startDate: Option[LocalDateTime] = None,
                    endDate: Option[LocalDateTime] = None,
                    status: Int = 2,
                    sumId: Option[Int] = None) = {
    val startTime = System.currentTimeMillis()
    val dtformat = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")
    val oss = Await.result(if (sumId.isEmpty) {
      ossRep.ossFind(startDate, endDate, status)
    } else {
      ossRep.ossFind(sumId = sumId, status = 3)
    }, Duration.Inf)
    val result = oss.length
    logger.info("postAtNotSend(startDate, endDate, status, sumId, result) = " + (startDate, endDate, status, sumId, result).toString)
    val ossfe = for (ossInfo <- oss)
      yield (ossInfo, Await.result(ossRep.ossFeFind(ossInfo.id.getOrElse(0)), Duration.Inf))

    for (f <- ossfe) {
      val ossFeRes = f._2
      val ossInfo = f._1
      val r =
        if (ofc.isInFShopNumber(ossInfo.ossFShopNumber))
          (
            s"""{"Result":{"ResponseStatus":{"IsSuccess":true,"Errors":[],"SuccessEntitys":[
               |{"Id":${ossInfo.id.getOrElse(0)},"Number":"${ossInfo.ossFGYBillNo}","DIndex":0}],
               |"SuccessMessages":["此店铺不同步至金蝶"],"MsgCode":0},"Id":${ossInfo.id.getOrElse(0)},
               |"Number":"${ossInfo.ossFGYBillNo}","NeedReturnData":[{}]}}""".stripMargin)
        else if (ofc.isInFStockNumber(ossInfo.ossFStockNumber))
          (
            s"""{"Result":{"ResponseStatus":{"IsSuccess":true,"Errors":[],"SuccessEntitys":[
               |{"Id":${ossInfo.id.getOrElse(0)},"Number":"${ossInfo.ossFGYBillNo}","DIndex":0}],
               |"SuccessMessages":["此仓库不同步至金蝶"],"MsgCode":0},"Id":${ossInfo.id.getOrElse(0)},
               |"Number":"${ossInfo.ossFGYBillNo}","NeedReturnData":[{}]}}""".stripMargin)
        else {
          val tobPara = Json.arr("SAL_OUTSTOCK", getXSCKDParamBOS(ossInfo, ossFeRes))
          logger.debug(tobPara.toString())
          Await.result(kdPost.webApiSave(tobPara), Duration.Inf)
        }
      try {
        val res = Json.parse(r)

        /**
         * {
         * "Result": {
         * "ResponseStatus": {
         * "ErrorCode": 500,
         * "IsSuccess": false,
         * "Errors": [{
         * "FieldName": "FBillNo",
         * "Message": "违反字段唯一性要求：编码唯一。[XSCKD103XXSDO10011]在当前系统中已经被使用。",
         * "DIndex": 0
         * }, {
         * "FieldName": "",
         * "Message": "第三方单据编号【XXSDO10011】重复，不允许保存。",
         * "DIndex": 0
         * }],
         * "SuccessEntitys": [],
         * "SuccessMessages": [],
         * "MsgCode": 11
         * },
         * "Id": "",
         * "Number": "",
         * "NeedReturnData": [{}]
         * }
         * }
         */
        if (res("Result")("ResponseStatus")("IsSuccess").as[Boolean]) {
          ossRep.ossUpdateEnd(
            OutStockSum(
              id = ossInfo.id,
              ossResult = Some(r),
              ossStatus = 2,
              ossKDResultID = res("Result")("Number").asOpt[String]
            )
          )
        } else if (res("Result")("ResponseStatus")("MsgCode").as[Int] == 11) {
          val err = res("Result")("ResponseStatus")("Errors").as[Array[JsValue]]
          val msg = err(0)("Message").as[String]
          if (msg.startsWith("违反字段唯一性要求：编码唯一。") || msg.startsWith("第三方单据编号")) {
            val resultId = Option("[0-9A-Za-z]".r.findAllIn(msg).mkString)
            ossRep.ossUpdateEnd(OutStockSum(id = ossInfo.id, ossResult = Some(r), ossStatus = 2, ossKDResultID = resultId))
          } else {
            ossRep.ossUpdateEnd(OutStockSum(id = ossInfo.id, ossResult = Some(r), ossStatus = 1))
          }
        } else {
          ossRep.ossUpdateEnd(OutStockSum(id = ossInfo.id, ossResult = Some(r), ossStatus = 1))
        }
      } catch {
        case e: Exception => {
          logger.debug("SendOutStockSum Json.parse Exception:", e);
          ossRep.ossUpdateEnd(OutStockSum(id = ossInfo.id, ossResult = Some(r), ossStatus = 1))
        }
      }
    }
    s"""{
       |"date":"${LocalDateTime.now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"))}",
       |"RunTime": ${(System.currentTimeMillis() - startTime) / 1000.0},
       |"sdoCount": $result,
       |"result":"${startDate.getOrElse(LocalDateTime.now).toLocalDate}"
       |}""".stripMargin
  }

  def ossFEntityCount(p: OutStockPostParameters) = {
    logger.debug(p.toString)
    var result = new ListBuffer[String]
    try {
      val sDate = LocalDate.parse(p.sdate.substring(0, 10)) //.atZone(ZoneId.systemDefault()).toInstant
      val eDate = LocalDate.parse(p.sdate.substring(13)) //.atZone(ZoneId.systemDefault()).toInstant
      var startDate = sDate
      var endDate = eDate
      val dateLength = eDate.compareTo(sDate) + 1
      if (dateLength > 1) {
        startDate = sDate.plusDays(p.page * p.limit)
        if (eDate.compareTo(startDate) > 10) endDate = startDate.plusDays(p.limit - 1)
      }

      logger.debug(s"$startDate, \" ~ \", $endDate")
      var dateEnd = startDate
      while (dateEnd.compareTo(endDate) <= 0) {
        //println(dateEnd)
        val startDate = LocalDateTime.parse(dateEnd.toString + "T00:00:00")
        val endDate = LocalDateTime.parse(dateEnd.toString + "T00:00:00").plusDays(1)
        result += ossFEntityCountAtDays(startDate = Some(startDate), endDate = Some(endDate))
        dateEnd = dateEnd.plusDays(1)
      }
      Tuple2(result, dateLength)
    } catch {
      case e: Exception => logger.debug(s"ossFEntityCount=>sdate输入错误", e); Tuple2(result, 0)
    }

  }

  def ossFEntityCountAtDays(startDate: Option[LocalDateTime] = None, endDate: Option[LocalDateTime] = None) = {
    val startTime = System.currentTimeMillis()
    var sdoCount = 0
    var goodsCount = 0
    var AmountCount = 0.0
    var sendNull = 0
    var sendTrue = 0
    var sendFalse = 0
    var serviceAmount = 0.0
    Await.result(ossRep.ossFind(startDate, endDate, 99), Duration.Inf)
      .foreach { s =>
        sdoCount += Json.parse(s.ossSumInfo.getOrElse(""))("KeyCount").as[Int]
        s.ossStatus match {
          case 2 => sendTrue += 1;
          case 1 => sendFalse += 1;
          case _ => sendNull += 1
        }
        Await.result(ossRep.ossFeFind(s.id.getOrElse(0)), Duration.Inf).foreach { f =>
          goodsCount += f.ossFQty
          AmountCount += f.ossFAllAmount - f.ossFFeeAmount
          serviceAmount += f.ossFServiceAmount
        }
      }
    // return String
    "{\"date\":\"%s\",\"RunTime\":%.3f,\"sdoCount\":\"%s\",\"goodsCount\":\"%s\",\"AmountCount\":\"%s\",\"sendNull\":%d,\"sendTrue\":%d,\"sendFalse\":%d}"
      .format(
        startDate.getOrElse(LocalDateTime.now).toLocalDate,
        (System.currentTimeMillis() - startTime) / 1000.0,
        java.text.NumberFormat.getInstance.format(sdoCount),
        java.text.NumberFormat.getInstance.format(goodsCount),
        java.text.NumberFormat.getInstance.format(AmountCount),
        sendNull,
        sendTrue,
        sendFalse
      )
  }
}
